package com.hermit.qmst.UI.main;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.hermit.qmst.R;
import com.hermit.qmst.UI.activity.CooperationActivity;
import com.hermit.qmst.UI.activity.OpenUrlActivity;
import com.hermit.qmst.UI.activity.PayCardActivity;
import com.hermit.qmst.request.RequestTask;
import com.hermit.qmst.request.RequestTaskInterface;
import com.hermit.qmst.tools.Common;
import com.hermit.qmst.tools.FileUtils;
import com.hermit.qmst.tools.ImageDownLoader;
import com.hermit.qmst.tools.ParseXML;
import com.hermit.qmst.tools.Preferences;

import org.json.JSONArray;
import org.json.JSONObject;


public class MoreFragment2 extends Fragment implements View.OnClickListener ,RequestTaskInterface {


    private TextView mTitle;
    private Preferences mPreferences;
    private RequestQueue mRequestQueue;
    private ProgressBar mProgressBar;
    private AlertDialog mProgressDialog;
    private TextView mtvShare;
    private TextView mtvAdsMarquee;

    private ImageView mImageView;
    private FileUtils mFileUtils;
    private ImageDownLoader mImageDownLoader;
    private String mUrl;
    private View mView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mImageDownLoader = new ImageDownLoader(getActivity());
        mFileUtils = new FileUtils();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        if (mView == null){
            mView = inflater.inflate(R.layout.activity_more, container, false);

        }else {

            ViewGroup vp =  (ViewGroup)mView.getRootView();
            vp.removeView(mView);

        }
        return mView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mPreferences = new Preferences(getActivity());
        if (mRequestQueue == null){
            mRequestQueue = Volley.newRequestQueue(getActivity());
            initView();
        }
        mRequestQueue.getCache().clear();




        //request_more_info();
        request_icon_content();
        request_ads_word();

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        if (mImageView == null) {
            mImageView = (ImageView) getActivity().findViewById(R.id.iv);
            mImageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    if (mUrl != null){
                        Intent intent = new Intent(getActivity(), OpenUrlActivity.class);
                        intent.putExtra("title","");
                        intent.putExtra("url",mUrl);
                        startActivity(intent);
                    }

                }
            });
            getlbAdsFromLocal(null);
        }

        request_web();
    }

    private void initView(){
        mTitle = (TextView)getActivity().findViewById(R.id.tv_title);
        mTitle.setText("");

        getActivity().findViewById(R.id.more_btn_1).setOnClickListener(this);
        getActivity().findViewById(R.id.more_btn_2).setOnClickListener(this);
        getActivity().findViewById(R.id.more_btn_3).setOnClickListener(this);
        getActivity().findViewById(R.id.more_btn_4).setOnClickListener(this);
        getActivity().findViewById(R.id.more_btn_5).setOnClickListener(this);
        getActivity().findViewById(R.id.more_btn_6).setOnClickListener(this);
        getActivity().findViewById(R.id.more_btn_7).setOnClickListener(this);
        getActivity().findViewById(R.id.more_btn_8).setOnClickListener(this);
        mtvShare = (TextView)getActivity().findViewById(R.id.tv_title_right);
        mtvShare.setText("分享  ");
        mtvShare.setVisibility(View.VISIBLE);
        mtvShare.setOnClickListener(this);
        mtvAdsMarquee = (TextView)getActivity().findViewById(R.id.tv_ads_marquee);


    }

    @Override
    public void onClick(View v) {

        Intent intent;

        switch (v.getId()){

            case R.id.more_btn_1:

                if (mPreferences.getPreferenceStringValue("2") != null) {

                    intent = new Intent(getActivity(), OpenUrlActivity.class);
                    intent.putExtra("title", "");
                    intent.putExtra("url", mPreferences.getPreferenceStringValue("2"));
                    getActivity().startActivity(intent);
                    getActivity().overridePendingTransition(R.anim.fling_in_right2left, R.anim.fling_out_left2right);
                }
                break;
            case R.id.more_btn_2:

                if (mPreferences.getPreferenceStringValue("3") != null) {
                    intent = new Intent(getActivity(), OpenUrlActivity.class);
                    intent.putExtra("title", "");
                    intent.putExtra("url", mPreferences.getPreferenceStringValue("3"));
                    getActivity().startActivity(intent);
                    getActivity().overridePendingTransition(R.anim.fling_in_right2left, R.anim.fling_out_left2right);
                }
                break;

            case R.id.more_btn_3:

                if (mPreferences.getPreferenceStringValue("1") != null) {
                    String msg = mPreferences.getPreferenceStringValue("1");
                    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                    builder.setMessage(msg);
                    builder.setTitle("提示");
                    builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            String phone = mPreferences.getPreferenceStringValue(Preferences.SERVICE_CALL);
                            if (phone != null && phone.length() > 0) {
                                dialog.dismiss();
                                Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phone));
                                startActivity(callIntent);
                            }
                        }
                    });
                    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    builder.create().show();
                }
                break;

            case R.id.more_btn_4:
//                if (mPreferences.getPreferenceStringValue("4") != null) {
//                    intent = new Intent(getActivity(), OpenUrlActivity.class);
//                    intent.putExtra("title", "");
//                    intent.putExtra("url", mPreferences.getPreferenceStringValue("4"));
//                    getActivity().startActivity(intent);
//                    getActivity().overridePendingTransition(R.anim.fling_in_right2left, R.anim.fling_out_left2right);
//                }

                intent = new Intent(getActivity(), CooperationActivity.class);
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.fling_in_right2left, R.anim.fling_out_left2right);
                break;

            case R.id.more_btn_5:

                intent = new Intent(getActivity(),FindFragment.class);
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.fling_in_right2left, R.anim.fling_out_left2right);

                break;

            case R.id.more_btn_6:
//                if (mPreferences.getPreferenceStringValue("5") != null) {
//                    intent = new Intent(getActivity(), OpenUrlActivity.class);
//                    intent.putExtra("title", "");
//                    intent.putExtra("url", mPreferences.getPreferenceStringValue("5"));
//                    getActivity().startActivity(intent);
//                    getActivity().overridePendingTransition(R.anim.fling_in_right2left, R.anim.fling_out_left2right);
//                }

                intent = new Intent(getActivity(), PayCardActivity.class);
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.fling_in_right2left, R.anim.fling_out_left2right);

                break;

            case R.id.more_btn_7:
                request_sign();

                break;
            case R.id.more_btn_8:
                intent = new Intent(getActivity(), MoreFragment.class);
                intent.putExtra("mianfeichoujiang", mPreferences.getPreferenceStringValue("4"));
                intent.putExtra("惠赚钱", mPreferences.getPreferenceStringValue("5"));
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.fling_in_right2left,R.anim.fling_out_left2right);

                break;

        }
    }


    private void request_more_info(){

        mRequestQueue.getCache().clear();
        String url = Common.submitQueryMoreInfoPath();

        StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {

                try{
                    if (ParseXML.parseResponseXML(s, "Ret").equals("0")){
                        String service_call = ParseXML.parseResponseXML(s,"service_call");
                        if (service_call != null && service_call.length() > 0){

                            mPreferences.setPreferenceStringValue(Preferences.SERVICE_CALL,service_call);
                        }else {

                            mPreferences.setPreferenceStringValue(Preferences.SERVICE_CALL,null);
                        }

                        String website = ParseXML.parseResponseXML(s,"website");
                        if (website != null && website.length() > 0){
                            mPreferences.setPreferenceStringValue(Preferences.WEBSITE,website);
                        }else {
                            mPreferences.setPreferenceStringValue(Preferences.WEBSITE,null);
                        }
                    }
                }catch (Exception e){

                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        })
        {
            @Override
            public byte[] getBody() {
                String requestParam =  "<?xml version=\"1.0\" encoding=\"UTF-8\"?><data><type>more_info</type><uid>"+Common.mInfoId+"</uid><phone>"+ Common.myPhone +"</phone></data>";
                byte[] b = null;
                try {
                    b = requestParam.getBytes("utf-8");
                }catch (Exception e){
                    b = requestParam.getBytes();
                }
                return b;
            }
        };

        mRequestQueue.add(request);


    }

    private void request_ads_word(){
        String url = Common.submitQueryTextPath();
        String param =  "<?xml version=\"1.0\" encoding=\"UTF-8\"?><data><type>find_word</type><uid>"+Common.mInfoId+"</uid><phone>"+ Common.myPhone +"</phone></data>";
        RequestTask task = new RequestTask(this,url,param,"POST",getActivity());
        task.execute();
    }

        private void request_sign(){

            mProgressDialog = ProgressDialog.show(getActivity(), "提示", "系统正在处理，请稍后…", false, false);
            mProgressDialog.setCancelable(true);
        RequestQueue requestQueue = Volley.newRequestQueue(getActivity());

        String url = Common.submitSignPath() + "regnum=" + Common.myPhone + "&regpwd=" + Common.myPassword;

        StringRequest request = new StringRequest(Request.Method.POST,url,new Response.Listener<String>(){

            @Override
            public void onResponse(String s) {

                if (s != null && s.length() > 0){

                 if (ParseXML.parseResponseXML(s,"Ret").equals("2")){

                     Toast.makeText(getActivity(), "今日已签到", Toast.LENGTH_LONG).show();
                 }else if (ParseXML.parseResponseXML(s,"Ret").equals("0")){

                     String m = ParseXML.parseResponseXML(s, "balance");

                     Toast.makeText(getActivity(), "赠送" + m + "元", Toast.LENGTH_LONG).show();

                 }else {
                     Toast.makeText(getActivity(), "失败", Toast.LENGTH_LONG).show();
                 }

                //
                }else {

                    Toast.makeText(getActivity(), "出错", Toast.LENGTH_LONG).show();
                }
                mProgressDialog.dismiss();
            }
        },new Response.ErrorListener(){
            @Override
            public void onErrorResponse(VolleyError volleyError) {

                Toast.makeText(getActivity(), "出错", Toast.LENGTH_LONG).show();
            }
        });


        requestQueue.add(request);


    }

    //请求精品推荐信息
    private void request_web(){
        String url = Common.submitQueryPicPath();
        String param =   "<?xml version=\"1.0\" encoding=\"UTF-8\"?><data><type>find_pic</type><uid>"+Common.mInfoId+"</uid><phone>"+ Common.myPhone +"</phone></data>";
        RequestTask task = new RequestTask(new RequestTaskInterface() {
            @Override
            public void postExecute(String paramString) {

                if (paramString != null) {

                    try {
                        JSONObject jsonObject = new JSONObject(paramString);
                        if ( jsonObject.getInt("status") == 1) {

                            JSONArray dataArr = jsonObject.getJSONArray("data");


                            getlbAdsFromLocal(dataArr);

                        } else {

                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }, url, param, "POST", getActivity());
        task.execute();
    }


    //图标内容
    private void request_icon_content(){
        String url = Common.submitQueryTextPath();
        String param =   "<?xml version=\"1.0\" encoding=\"UTF-8\"?><data><type>find_icon_url</type><uid>"+Common.mInfoId+"</uid><phone>"+ Common.myPhone +"</phone></data>";
        RequestTask task = new RequestTask(new RequestTaskInterface() {
            @Override
            public void postExecute(String paramString) {

                if (paramString != null) {

                    try {
                        JSONObject jsonObject = new JSONObject(paramString);
                        if ( jsonObject.getInt("status") == 1) {

                            JSONArray dataArr = jsonObject.getJSONArray("data");

                            for (int i = 0; i < dataArr.length();i++){

                                JSONObject jo = dataArr.getJSONObject(i);
                                mPreferences.setPreferenceStringValue(jo.getString("type"),jo.getString("url"));

                            }



                        } else {

                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }, url, param, "POST", getActivity());
        task.execute();
    }


    //从本地获取广告
    private void getlbAdsFromLocal( JSONArray dataArr){

        JSONArray array = null;
        if (dataArr == null){//从本地获取保存的数据
            try{
                String str = mFileUtils.readTxt(Common.getDialImageDirPath(),Common.mFindTxtFileName);
                if (str == null){
                    return;
                }


                array = new JSONArray(str);

            }catch (Exception e){
                e.printStackTrace();
            }

        }else {
            array = dataArr;
        }
        //读取图片
        try{
            JSONObject jsonObject = array.getJSONObject(0);
            if (!jsonObject.getString("img").equals("")){


                String imgUrl = jsonObject.getString("img");
                mUrl = jsonObject.getString("url");
                Bitmap bitmap = mImageDownLoader.downloadImage(Common.getDialImageDirPath(),imgUrl,new ImageDownLoader.onImageLoaderListener() {
                    @Override
                    public void onImageLoader(Bitmap bitmap, String url) {


                        Drawable drawable = new BitmapDrawable(getActivity().getResources(), bitmap);
                        mImageView.setBackgroundDrawable(drawable);
                    }
                });

                if (bitmap != null){
                    Drawable drawable = new BitmapDrawable(getActivity().getResources(), bitmap);
                    mImageView.setBackgroundDrawable(drawable);
                }

            }



        }catch (Exception e){
            e.printStackTrace();
        }

        if (dataArr != null){
            try{
                mFileUtils.saveTxtFile(Common.getDialImageDirPath(),Common.mFindTxtFileName,array.toString());
            }catch (Exception e){
                e.printStackTrace();
            }
        }


    }

    @Override
    public void postExecute(String paramString) {
        if (paramString == null || paramString.length() == 0 ){
            return;
        }

        try{

            JSONObject jsonObject = new JSONObject(paramString);
            if (jsonObject.getString("status").equals("1")){
                JSONArray dataArr = jsonObject.getJSONArray("data");
                if (dataArr.length() > 0){
                    JSONObject item = dataArr.getJSONObject(0);
                    String str = item.getString("content");
                    mtvAdsMarquee.setText(str);
                    mtvAdsMarquee.setSelected(true);
                }
            }

        }catch (Exception e){

        }
    }
}
